import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import moment from 'moment';
import { Table, Button, Card, Modal, Form, Icon, Input, Menu, Dropdown, message, TreeSelect, Select, Switch, Row, Col,Upload } from 'antd';
import StandardTable from '../../components/StandardTable';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import styles from '../Mana/Role.less';

/*校区管理-学校管理*/
const FormItem = Form.Item;
const { Option } = Select;
const getValue = obj =>Object.keys(obj).map(key => obj[key]).join(',');

//默认状态
var state;
var treeData =[];//tree  机构 data
//图片
var headerimg="";
var imageUrl="";
//图片
function getBase64(img, callback) {
  const reader = new FileReader();
  reader.addEventListener('load', () => callback(reader.result));
  reader.readAsDataURL(img);
}

class Avatar extends React.Component {
  state = {  loading: false };
  handleChange = (info) => {
    if (info.file.status === 'uploading') {
      this.setState({ loading: true });
      return;
    }
    if(info.file.status === 'done') {
    	headerimg=info.file.response.obj.path;
    	imageUrl=info.file.response.obj.path;
	    getBase64(info.file.originFileObj, imageUrl => this.setState({
	        imageUrl,
	        loading: false,
	    }));
    }
  }
  render() {
    const uploadButton = (
      <div>
        <Icon type={this.state.loading ? 'loading' : 'plus'} />
        <div className="ant-upload-text">Upload</div>
      </div>
    );
	  if(imageUrl==undefined){
	  	 imageUrl = this.state.imageUrl;
	  }else{
	  	headerimg=imageUrl;
	  }
    const urls="api/web/attachment/upload.manage?token="+sessionStorage.getItem('token');
    return (
      <Upload
        name="file"
        style={{width:'200px'}}
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        action={urls}
        method="POST"
        enctype="multipart/form-data"
        onChange={this.handleChange}
      >
        {imageUrl ? <img src={imageUrl} alt=""  style={{width:'200px'}} /> : uploadButton}
      </Upload>
    );
  }
}

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible,title,obj} = props;
  const {getFieldDecorator} = form;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
	      if(fieldsValue.state == undefined) { 	fieldsValue.state = 1}
				fieldsValue.url=headerimg;
	      form.resetFields();
	      handleAdd(title,obj.schoolId,fieldsValue);
    });
  };
  if(title == "编辑"){
  	 return (
    <Modal
      maskClosable={false}
      destroyOnClose={true}
      width={'60%'}
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false,'','')}
    >
    <Form layout="horizontal">
	          <FormItem label="学校名称12" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('name', {
	            	 initialValue:obj.name,
	              rules: [{ required: true, message: '学校名称不能为空!' }],
	            })(<Input placeholder="请输入"/>)}
          	</FormItem>
         	 <FormItem label="机构" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('orgId',{
            	 initialValue:obj.orgId,
            	 rules: [{ required: true, message: '机构不能为空!' }],
            })(<TreeSelect  dropdownMatchSelectWidth   treeDefaultExpandAll   allowClear
			        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}   placeholder="请选择上级机构"
			        treeData={treeData} ></TreeSelect>
            )}
          </FormItem>
          <FormItem label="地址" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('addr', {
            	initialValue:obj.addr,
              rules: [{ required: true, message: '地址不能为空!' }],
            })(<Input placeholder="请输入"/>)}
          </FormItem>
          <FormItem label="ico" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('ico', {
            	initialValue:obj.ico==undefined ? "bars":obj.ico,
            })(<Select  placeholder="请选择菜单类型" allowClear>
				      <Option value="bars" className={styles.optionss}><Icon type="bars" /></Option>
				      <Option value="folder-open" className={styles.optionss}><Icon type="folder-open" /></Option>
				      <Option value="solution" className={styles.optionss}><Icon type="solution" /></Option>
				      <Option value="setting" className={styles.optionss}><Icon type="setting" /></Option>
				      <Option value="bar-chart" className={styles.optionss}><Icon type="bar-chart" /></Option>
				      <Option value="shopping-cart" className={styles.optionss}><Icon type="shopping-cart" /></Option>
				      <Option value="video-camera" className={styles.optionss}><Icon type="video-camera" /></Option>
				      <Option value="team" className={styles.optionss}><Icon type="team" /></Option>
				      <Option value="picture" className={styles.optionss}><Icon type="picture" /></Option>
				      <Option value="pause" className={styles.optionss}><Icon type="pause" /></Option>
				      <Option value="clock-circle" className={styles.optionss}><Icon type="clock-circle" /></Option>
			    </Select>)}
          </FormItem>
          <FormItem label="学校图片" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {(<Avatar />)}
          </FormItem>
          <FormItem label="状态" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('state', {
            	initialValue:obj.state==undefined ? "1":obj.state,
            	rules: [{ required: true, message: '状态不能为空!' }],
            })(<Select placeholder="请选择状态">
              <Option value="1">有效</Option>
              <Option value="0">无效</Option>
            </Select>)}
          </FormItem>
        </Form>
    </Modal>
  );
  }else{
  return (
    <Modal
      maskClosable={false}
      destroyOnClose={true}
      width={'60%'}
      title={title}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible(false,'','')}
    >
    <Form layout="horizontal">
	          <FormItem label="学校名称" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
	            {getFieldDecorator('name', {
	            	 initialValue:obj.name,
	              rules: [{ required: true, message: '学校名称不能为空!' }],
	            })(<Input placeholder="请输入"/>)}
          	</FormItem>
         	 <FormItem label="机构" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('orgId',{
            	 initialValue:obj.orgId,
            	 rules: [{ required: true, message: '机构不能为空!' }],
            })(<TreeSelect  dropdownMatchSelectWidth   treeDefaultExpandAll   allowClear
			        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}   placeholder="请选择上级机构"
			        treeData={treeData} ></TreeSelect>
            )}
          </FormItem>
          <FormItem label="地址" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('addr', {
            	initialValue:obj.addr,
              rules: [{ required: true, message: '地址不能为空!' }],
            })(<Input placeholder="请输入"/>)}
          </FormItem>
          <FormItem label="ico" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('ico', {
            	initialValue:obj.ico==undefined ? "bars":obj.ico,
            })(<Select  placeholder="请选择菜单类型" allowClear>
				      <Option value="bars" className={styles.optionss}><Icon type="bars" /></Option>
				      <Option value="folder-open" className={styles.optionss}><Icon type="folder-open" /></Option>
				      <Option value="solution" className={styles.optionss}><Icon type="solution" /></Option>
				      <Option value="setting" className={styles.optionss}><Icon type="setting" /></Option>
				      <Option value="bar-chart" className={styles.optionss}><Icon type="bar-chart" /></Option>
				      <Option value="shopping-cart" className={styles.optionss}><Icon type="shopping-cart" /></Option>
				      <Option value="video-camera" className={styles.optionss}><Icon type="video-camera" /></Option>
				      <Option value="team" className={styles.optionss}><Icon type="team" /></Option>
				      <Option value="picture" className={styles.optionss}><Icon type="picture" /></Option>
				      <Option value="pause" className={styles.optionss}><Icon type="pause" /></Option>
				      <Option value="clock-circle" className={styles.optionss}><Icon type="clock-circle" /></Option>
			    </Select>)}
          </FormItem>
          <FormItem label="学校图片" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {(<Avatar />)}
          </FormItem>
          <FormItem label="状态" labelCol={{span: 4}}  wrapperCol={{span: 18}}>
            {getFieldDecorator('state', {
            	initialValue:obj.state==undefined ? "1":obj.state,
            	rules: [{ required: true, message: '状态不能为空!' }],
            })(<Select placeholder="请选择状态">
              <Option value="1">有效</Option>
              <Option value="0">无效</Option>
            </Select>)}
          </FormItem>
        </Form>
    </Modal>
  );
  }
});

@connect(({ campuschool, loading ,menu }) => ({
  campuschool,
  loading: loading.models.campuschool,
  threeMenu: menu.threeMenu,
}))
@Form.create()
export default class TableList extends PureComponent {
	state = {
	    modalVisible: false,
	    selectedRows: [],
	    formValues: {},
	    obj: "",
	};
    componentDidMount() {
			//默认查询table 数据
			this.props.dispatch({
				type: 'campuschool/fetch_school',
				payload: {
					state :1,
				},
			});
			/*按钮查询*/
			this.props.dispatch({
				type: 'menu/fetch_three_menu',
			});
			//默认查询tree
			this.props.dispatch({
				type: 'campuschool/fetch_organ_tree',
				callback: (res,data) => {
					treeData=[];
					if(res==1){
						treeData=data;
					}
		    },
			});
	}

	handleStandardTableChange = (pagination, filtersArg, sorter) => {
	    const { dispatch } = this.props;
	    const { formValues } = this.state;
	    const filters = Object.keys(filtersArg).reduce((obj, key) => {
	    const newObj = { ...obj };
	      newObj[key] = getValue(filtersArg[key]);
	      return newObj;
	    }, {});
	    const params = {
	      currentPage: pagination.current,
	      pageSize: pagination.pageSize,
	      ...formValues,
	      ...filters,
	    };
	    if (sorter.field) {
	      params.sorter = `${sorter.field}_${sorter.order}`;
	    }
	    dispatch({
	      type: 'campuschool/fetch_school',
	      payload: params,
	    });
	};
	handleSelectRows = rows => {
	    this.setState({
	      selectedRows: rows,
	    });

	};
	/*重置*/
	handleFormReset = () => {
		const {	form,	dispatch} = this.props;
		form.resetFields();
		this.setState({	formValues: {},});
		dispatch({type: 'campuschool/fetch_school',});
	}
	/*查询*/
	handleSearch = e => {
	    e.preventDefault();
	    const { dispatch, form } = this.props;
	    form.validateFields((err, fieldsValue) => {
		    if (err) return;
		    const values = {  ...fieldsValue,};
		    this.setState({ formValues: values,});
		 	 	if(values.name==undefined){	values.name=""}
				if(values.partId==undefined){	values.partId=""}
				if(values.type==undefined){	values.type=""}
				if(values.addrCode==undefined){	values.addrCode=""}
				if(values.state==undefined){	values.state=""}
				if(values.orgId==undefined){	values.orgId=""}
				if(values.addr==undefined){	values.addr=""}
	        dispatch({
		        type: 'campuschool/fetch_school',
		        payload:{...values},
	        });
	    });
	};
	/*弹窗*/
  handleModalVisible = (flag,record,title) => {
  	const { selectedRows } = this.state;
	  	imageUrl="";
	  	if(flag==false){
	  		this.setState({
		      modalVisible: false,
		    });
	  	}else{
	  		var obj={};
	  		if(title=="新建"){
		  		this.setState({
			      modalVisible: !!flag,
			      title: title,
			      obj: obj,
			    });
	  		}else{
		  		if(record==undefined||Object.keys(selectedRows).length==0){
			    	message.info("还未选择项");
			    }else if(Object.keys(selectedRows).length>1){
			    	message.info("只可选择一项");
			    }else{
			    	selectedRows[0].orgId+=''
						selectedRows[0].state+=''
						if(selectedRows[0].url!=undefined){
							imageUrl=selectedRows[0].url
						}
					  obj=selectedRows[0];
					  this.setState({
				      modalVisible: !!flag,
				      title: title,
				      obj: obj,
				    });
			    }
		  	}

	  	}
  	};
	/*新增,修改*/
	handleAdd = (title,Id,fields) => {
	  	if(title=="新建"){
		    this.props.dispatch({
		      type: 'campuschool/add_school',
		      payload: {...fields,},
		      callback: (res,resMsg) => {
		      	if(res==1){
		      		message.success(resMsg);
		      	}else{
		      		message.error(resMsg);
		      	}
		      },
		    });
	  	}else if(title=="编辑"){
	  		this.props.dispatch({
		      type: 'campuschool/edit_school',
		      payload: {
		      	...fields,
		      	schoolId:Id,
		      },
		      callback: (res,resMsg) => {
						this.state.selectedRows=[];
		      	if(res==1){
		      		message.success(resMsg);
		      	}else{
		      		message.error(resMsg);
		      	}
		      },
		    });
	  	}
	    this.setState({
	      modalVisible: false,
	    });
	};

  /*删除*/
 	confirmModel=(title,Id)=>{
 		const { dispatch } = this.props;
    	const { selectedRows } = this.state;
	    if(Id==undefined&&Object.keys(selectedRows).length==0){
	    	message.info("还未选择项");
	    }else{
	    	var Ids=[];
		    if(Id!=undefined){
		    	Ids=Id;
		    }else if(selectedRows!=null){
		    	Ids.push(selectedRows.map(row => row.schoolId).join(','));
		    }
		    if(title!="删除"){
		    	var state;
		    	if(title=="禁用"){
		    		state=0;
		    	}else{
		    		state=1;
		    	}
		    	Modal.confirm({
						title: '是否'+title+'选中项状态?',
						okText: '确定',
						cancelText: '取消',
						onOk() {
							/*批量修改状态*/
							dispatch({
								type: 'campuschool/edit_school_state',
								payload: {
									schoolIds:Ids,
									state:state,
								},
								callback: (res, resMsg) => {
									if(res == 1) {
										message.success(resMsg);
									} else {
										message.error(resMsg);
									}
								},
							});
						}
					});
	    	}else{
	    		Modal.confirm({
				    title: '是否删除当前数据选中',
				    content: '',
				    onOk() {
				      dispatch({
					      type: 'campuschool/remove_school',
					      payload: {schoolIds:Ids,},
					      callback: (res,resMsg) => {
					      	if(res==1){
					      		message.success(resMsg);
					      	}else{
					      		message.error(resMsg);
					      	}
					      },
					  	});
				    },
				});
	    }
	  }
 	}
	renderSimpleForm() {
	    const { getFieldDecorator } = this.props.form;
	    return (
	      	<Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
           <Col md={8} sm={24}>
            <FormItem label="学校名称">
              {getFieldDecorator('name')(
                <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="所属机构">
              {getFieldDecorator('orgId')(
                <TreeSelect  dropdownMatchSelectWidth   treeDefaultExpandAll   allowClear
				        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}   placeholder="请选择上级机构"
				        treeData={treeData}
				      >
			    </TreeSelect>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label="学校地址">
              {getFieldDecorator('addr')(
               <Input placeholder="请输入" />
              )}
            </FormItem>
          </Col>
        </Row>
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="学校状态">
              {getFieldDecorator('state')(
                <Select placeholder="请选择" style={{ width: '100%' }}>
                  <Option value="1">有效</Option>
                  <Option value="0">无效</Option>
                </Select>
              )}
            </FormItem>
          </Col>
           <Col md={16} sm={24}>
            <FormItem>
	            <span style={{ float: 'right', marginBottom: 24 }}>
	            <Button type="primary" htmlType="submit">查询</Button>
	            <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>重置</Button>
	            </span>
            </FormItem>
          </Col>
        </Row>
      </Form>
	    );
	}
	render() {
	    const { campuschool: { data }, loading ,threeMenu} = this.props;
	    const { selectedRows, modalVisible,title,obj } = this.state;
	    const columns = [
				{
				title: '序号',
					dataIndex: 'schoolId',
					key: 'schoolId',
					width:'70px',
					render: (text, record, index) => {	return index + 1},
				},
				{
					title: '学校名称',
					dataIndex: 'name',
					key: 'name',
					width:'200px',
				}, {
					title: '所属机构',
					dataIndex: 'orgName',
					key: 'orgName',
					width:'150px',
				},{
					title: '地址',
					dataIndex: 'addr',
					key: 'addr',
					width:'220px',
				},{
					title: '图片',
					dataIndex: 'url',
					key: 'url',
					width:'80px',
					render: val => <img src={val} style={{width:'50px'}} />,
				},
				{
					title: '状态',
					dataIndex: 'state',
					key: 'state',
					width:'100px',
					render: (text, record, index) =>{
						if(record.state==1){
							return "有效"
						}else if(record.state==0){
							return "无效"
						}
					}
				}
			];
	    const parentMethods = {
	      	handleAdd: this.handleAdd,
	      	handleModalVisible: this.handleModalVisible,
	      	confirmModel:this.confirmModel,
	    };
	    return (
	    	<PageHeaderLayout title="校区系统/学校管理">
	      	<Card bordered={false}>
	          <div className={styles.tableList}>
	            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
	            <span>
	            	<Button type="primary" onClick={() => this.handleModalVisible(true,'','新建')} style={{ marginLeft: 8 }}>新建</Button>
	            	<Button type="primary"  onClick={() => this.handleModalVisible(true,'','编辑')} style={{ marginLeft: 8 }}>编辑</Button>
				      	{/*{threeMenu.delete && <Button type="primary" onClick={() => this.confirmModel('删除')} style={{ marginLeft: 8 }}>删除</Button>}*/}
				      	{threeMenu.enable && <Button type="primary"  onClick={() => this.confirmModel('启用')} style={{ marginLeft: 8 }}>启用</Button>}
				      	{threeMenu.enable && <Button type="ghost"  onClick={() => this.confirmModel('禁用')} style={{ marginLeft: 8 }}>禁用</Button>}
	            </span>
	            <StandardTable
	              selectedRows={selectedRows}
	              loading={loading}
	              data={data}
	              columns={columns}
	              onSelectRow={this.handleSelectRows}
	              onChange={this.handleStandardTableChange}
	            />
	          </div>
	        <CreateForm {...parentMethods} modalVisible={modalVisible} title={title} obj={obj}/>
	      </Card>
	    </PageHeaderLayout>
	    );
	}
}
